<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

require_once 'MainPageWidget.php';
class NodeItemsWidget extends MainPageWidget {
	public $title = 'Последние сообщения';
  public $from = 'node';
  public $community = array();
  public $community_list = array();
  public $tdi = array();
  public $tdi_list = array();
  public $ftype = 'all';
  public $itemscount = 10;
  public $widget_view = 'WG_NodeItemsWidget';
  
  private $items_count = 10;
  
	public function Render() {
		$this->ctx->rh->UseClass('RL_CyrDate');
		$this->ctx->rh->UseClass("RL_URLGenerator");
    $this->ctx->rh->UseClass('stores_ImageStorage');
    
    $this->itemscount+=0;
    if ( empty($this->itemscount) ) {
      $this->itemscount = $this->items_count;
    }
    
		$content['title'] = $this->getParam("title");
    $content['from'] = $this->getParam("from");
    $content['ftype'] = $this->getParam("ftype");
    
    $user_oids = $this->getUserOIDs();
    
    if ( 'node' == $this->from ) {
      $sql = 'select (select count(*) FROM t_acl_tree as node ' .
      ' left join t_acl_tree as parent on parent.lft <= node.lft and parent.rgt >= node.rgt ' .
      ' left outer join t_acl_list on parent.id_object = t_acl_list.id_acl_tree ' .
      ' where node.id_object = a.oid ' .
      ' and t_acl_list.id_subject in ( ' . join(',', $user_oids) . ' ) ' .
      ' and t_acl_list.`action` = "item_read" ' .
      ' AND t_acl_list.opt = 2) as disabled, a.oid, o.ctime ' .
      " from {$this->ctx->store->db->db_prefix}class_allfeed a " .
      " left join {$this->ctx->store->db->db_prefix}objects o on o.oid = a.oid " .
      ' where o.is_deleted = 0 and a.community_oid > 0 ';
      
      if ( 'all' != $this->ftype ) {
        $ftype = mysql_real_escape_string($this->ftype);
        $sql .= " and o.type = '{$ftype}' ";
      }
      
      $sql .= ' having `disabled` = 0 ' .
      ' order by o.ctime desc, o.oid desc limit ' . ($this->itemscount+0);
      
      //print $sql;exit;
    } else {
      $communityWhere = array();
      foreach ( $this->community_list as $community_oid ) {
        $tdi = $this->getTdiList( $community_oid );
        
        if ( !empty($tdi) ) {
          $tdi_list = array();
          
          foreach ( $this->tdi_list as $tdi_oid ) {
            foreach ($tdi as $val) {
              if ( $tdi_oid == $val['oid'] || 0 == $tdi_oid ) {
                $tdi_list[] = $tdi_oid;
                break;
              }
            }
          }
          
          $communityWhere[] = "(a.community_oid = {$community_oid} and a.tdi_oid in (" . join(',', $tdi_list) . '))';
        } else {
          $communityWhere[] = "a.community_oid = {$community_oid}";
        }
      }
      
      $community_string = '(' . join(' or ', $communityWhere) . ')';
      
      $sql = 'select (select count(*) FROM t_acl_tree as node ' .
      ' left join t_acl_tree as parent on parent.lft <= node.lft and parent.rgt >= node.rgt ' .
      ' left outer join t_acl_list on parent.id_object = t_acl_list.id_acl_tree ' .
      ' where node.id_object = a.oid ' .
      ' and t_acl_list.id_subject in ( ' . join(',', $user_oids) . ' ) ' .
      ' and t_acl_list.`action` in ("item_read", "comment_read") ' .
      ' and t_acl_list.opt = 2) as disabled, a.oid, o.ctime ' .
      " from {$this->ctx->store->db->db_prefix}class_allfeed a " .
      " left join {$this->ctx->store->db->db_prefix}objects o on o.oid = a.oid " .
      ' where o.is_deleted = 0 and a.community_oid > 0 ' .
      " and {$community_string} ";
      
      if ( 'all' != $this->ftype ) {
        $ftype = mysql_real_escape_string($this->ftype);
        $sql .= " and o.type = '{$ftype}' ";
      }
      
      $sql .= ' having `disabled` = 0 ' .
      ' order by o.ctime desc limit ' . ($this->itemscount+0);
      
      //print $sql;exit;
    }
    
    $result = $this->ctx->store->query($sql);
    
    if ( $result instanceof MysqlDBResult ) {
      while ( $row = $result->next() ) {
        $object = $this->ctx->store->getObject($row['oid']);
        
        if ( $object instanceof fobject ) {
          $date_obj = RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $row['ctime']);
          $object->data['ctime'] = $date_obj->format("%H:%i");
    			$activity_date = $date_obj->format("%j %b");
          
          $object->data['id'] = $object->id;
          $object->data['type'] = $object->type;
          
          if ( 'fimage' == $object->data['type']) {
            $img_obj = new ImageStorage( $this->ctx->store );
            $object->data['image'] = $img_obj->Get( $object->data['image_oid'] );
          }
          
          //if ( isset($object->data['text']) && !empty($object->data['text']) ) {
          //  $object->data['text'] = trim(strip_tags($object->data['text']));
          //  
          //  if ( mb_strlen($object->data['text']) > $this->max_text_length ) {
          //    $pos = mb_strrpos( mb_substr($object->data['text'], 0, $this->max_text_length), ' ' );
          //    $object->data['text'] = mb_substr( $object->data['text'], 0, $pos ) . '...';
          //  }
          //}
          
          $object->data['date'] = $activity_date;
          
          $user = $this->ctx->store->getObject($object->data['posted_by_id']);
          $user->data['oid'] = $object->data['posted_by_id'];
          $object->data['user'] = $user->data;
          
          $item = $this->ctx->store->getObject($object->data['id']);
          
          if ( 'ffile' == $item->type ) {
            $query['filestorage']['oid']['=='] = $object->data['file_oid'];
            $find_result = $this->ctx->store->find( $query );
            if ( $find_result instanceof DBStoreResult ) {
              $file = $find_result->next();
              $item->data['file'] = $file->data;
            }
          }
          
          $object->data['item'] = $item->data;
          
          $community = $this->ctx->store->getObject($item->data['community_oid']);
          $object->data['community'] = $community->data;
          
          $object->data['comments_count'] = $this->getCommentsCount($object->id);
          
          $content['items'][$activity_date][] = $object->data;
        }
      }
    }
    
    if ( !empty($content['items']) ) {
      $this->content = $content;
    }
    
  	return $this;
  }
  
  public function settingsForm() {
    if ( empty($this->community) ) {
      $rs = $this->ctx->store->find("objects where objects.type = :0 and objects.is_deleted=0 order by objects.ctime desc", array("fcommunity"));
  		while ($obj = $rs->next()) {
  			$this->community[] = array_merge($obj->data, array(
  				'oid' => $obj->id
  			));
  		}
    }
    
    foreach ( $this->community as $key=>$val ) {
      foreach ( $this->community_list as $oid ) {
        if ( $oid == $val['oid'] ) {
          $this->community[$key]['checked'] = true;
          break;
        }
      }
      $tdi_list = $this->getTdiList( $val['oid'] );
      
      foreach ($tdi_list as $index=>$tdi) {
        foreach ($this->tdi_list as $present) {
          if ( $present == $tdi['oid'] ) {
            $tdi_list[$index]['checked'] = true;
          } else if ( 0 == $present && isset($this->community[$key]['checked'])
          && $this->community[$key]['checked']) {
            $this->community[$key]['root_checked'] = true;
          }
        }
      }
      
      $this->community[$key]['tdi'] = $tdi_list;
    }
    
		if ( !isset($this->params) || !isset($this->params['title']) ) {
			$this->params['title'] = $this->title;
      $this->params['from'] = $this->from;
      $this->params['community'] = $this->community;
		}
    
		//return $this->params;
	}
  
  public function setParams( $params ) {
    foreach ( $params as $key=>$val ) {
      if ( isset($this->$key) ) {
        $this->$key = $val;
      }
    }
  }
  
  private function getUserOIDs() {
    $user_oids = array();
    
    if ( isset($this->ctx->mm->aa) && !empty($this->ctx->mm->aa) ) {
      $aa = $this->ctx->mm->aa;
      if ( isset($aa->acl_data['user_id']) && !empty($aa->acl_data['user_id']) ) {
        $user_oids[] = $aa->acl_data['user_id'];
      }
      if ( isset($aa->acl_data['role']['oid']) && !empty($aa->acl_data['role']['oid']) ) {
        $user_oids[] = $aa->acl_data['role']['oid'];
      }
    }
    return $user_oids;
  }
  
  private function getCommentsCount( $item_oid ) {
    $sql = "select count(*) as count from {$this->ctx->store->db->db_prefix}class_comment c " .
    " left join {$this->ctx->store->db->db_prefix}objects o on o.oid = c.oid " .
    " where o.is_deleted = 0 and c.item_oid = {$item_oid}";
    
    $result = $this->ctx->store->query( $sql );
    if ( !($result instanceof MysqlDBResult) ) {
      return 0;
    }
    
    $row = $result->next();
    if ( empty($row) || !isset($row['count']) ) {
      return 0;
    }
    
    return $row['count'];
  }
}